import base64
import logging
import uuid

from rest_framework.views import APIView
from collections import OrderedDict

from apps.baseData.models import User, ScoreDetails
from apps.need.models import Need, Tags, Images, Video
from apps.need.serializers import NeedSerializer
from config import Aliyun
from utils import AliyunUtil
from utils.network import Result, MyPageNumber, is_login, CustomGenericViewSet

logger = logging.getLogger(__name__)


class NeedListView(APIView):
    """获取分类下的需求"""

    def get(self, request):
        """
        获取分类下的需求并分页显示

        'page': openapi.Schema(type=openapi.TYPE_INTEGER, description="页码"),

        'id': openapi.Schema(type=openapi.TYPE_INTEGER, description="标签的id"),

        'region': openapi.Schema(type=openapi.TYPE_INTEGER, description="地区的id，默认全部"),

         required=['id'],

        """
        # 新的在上面
        need_list = Need.objects \
            .filter(classify_id=int(request.GET['id']), status=Need.STATUS_CHOICES[1][0]) \
            .order_by('-update_time')

        page_obj = MyPageNumber()
        page_need = page_obj.paginate_queryset(queryset=need_list, request=request, view=self)
        ser_obj = NeedSerializer(page_need, many=True)
        data = ser_obj.data

        return Result.success(**OrderedDict([
            ('total', page_obj.page.paginator.count),
            ('next', page_obj.get_next_link()),
            ('page', int(request.GET['id'])),
            ('data', data)
        ]))

    @is_login()
    def post(self, request):
        """新增一个需求"""
        data = request.data
        serializer = NeedSerializer(data=data)
        serializer.is_valid(raise_exception=True)
        serializer.save()
        return Result.success(data=serializer.data)


class UserNeedListView(CustomGenericViewSet):
    """指定用户下的需求"""

    @is_login(key="user_obj")
    def post(self, request, user_obj):
        data = request.data
        page = int(request.data.get('page'))
        need_list = Need.objects.filter(status=data.get('status'), user=user_obj) \
            .order_by('-update_time')

        page_obj = MyPageNumber()
        page_need = page_obj.paginate_queryset(queryset=need_list, request=request, view=self)
        ser_obj = NeedSerializer(page_need, many=True)
        data = ser_obj.data

        return Result.success(**OrderedDict([
            ('total', page_obj.page.paginator.count),
            ('next', page_obj.get_next_link()),
            ('page', int(page)),
            ('data', data)
        ]))

    @is_login(key="user_obj")
    def off_shelf(self, request, user_obj):
        need = Need.objects.filter(user=user_obj, id=request.data.get('id')).first()
        # 如果订单已经被接单,取消订单扣分
        ScoreDetails(user=user_obj, status=False, score=need.money + 5)
        need.status = need.STATUS_CHOICES[4][0]
        need.save()
        ser_obj = NeedSerializer(need)
        return Result.success(data=ser_obj.data)


class NeedItemView(CustomGenericViewSet):
    serializer_class = NeedSerializer

    def item(self, request, pk):
        """"""
        need_item = Need.objects.get(id=int(pk))
        serializer = self.get_serializer(need_item)
        return Result.success(data=serializer.data)


class AddNeed(CustomGenericViewSet):
    @is_login(key='user_obj')
    def release(self, request, user_obj):
        data = request.data
        # content: this.content,
        # title: this.title,
        # money: this.money,
        # phone: this.phone,
        # address: this.locationAddress,
        # classify_id: this.classify_id
        need = Need(user=user_obj,
                    content=data.get('content'),
                    title=data['title'],
                    money=data['money'],
                    phone=data['phone'],
                    address=data['address'],
                    classify_id=data['classify_id'],
                    location=data['location'])
        need.save()
        # 创建标签
        if 'tags' in data.keys() and len(data['tags']) > 0:
            tgs = [Tags(name=i, need=need, user=user_obj) for i in str(data['tags']).split(',')]
            Tags.objects.bulk_create(tgs)
        # 加分
        sd = ScoreDetails(user=user_obj, status=True, score=data['money'])
        sd.save()

        serializer = NeedSerializer(need)
        return Result.success(data=serializer.data)

    @is_login(key='user_obj')
    def upload_need(self, request, user_obj):
        need_id = request.data.get('needId')
        nd = Need.objects.get(id=need_id)
        report_img = request.FILES.get('img')
        suffix = str(report_img.name).split('.')
        # 加上后缀
        filename = str(uuid.uuid4()) + '.' + suffix[len(suffix) - 1]
        _file = report_img.file
        try:
            response = AliyunUtil.upload_img(bucket_name=Aliyun.BUCKET, filename=Aliyun.Need_Path + filename,
                                             base64=_file)
            url = Aliyun.get_img_path(Aliyun.Need_Path + filename)
            Images.objects.create(url=url, need=nd)
            return Result.success(data=url, response=str(response))
        except Exception as e:
            logger.error(str(e))
            return Result.error(response=str(e))

    @is_login(key='user_obj')
    def delete(self, request, user_obj: User):
        need = Need.objects.get(id=request.data.get('id'))
        if need.user_id != user_obj.id:
            return Result.error(message='用户不正确')
        # 删除所有外键
        Images.objects.filter(need=need).delete()
        Video.objects.filter(need=need).delete()
        Tags.objects.filter(need=need).delete()
        need.delete()
        return Result.success()
